package com.example.webcrawlercoursedesign;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class Fragment163 extends Fragment {
	private Context context;
	private List<News> newsList;//添加新闻
	private NewsAdapter adapter;//新闻适配器
	private Handler handler;
	private ListView listView;//展示新闻列表
	private NewsCache cache;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		context = getActivity();
		//fragment的布局
		View fragmentView = inflater.inflate(R.layout.fragment_163, container, false);
		newsList = new ArrayList<>();//新闻列表
		listView = fragmentView.findViewById(android.R.id.list);
		cache = new NewsCache(context);
		getNews(context);//获取新闻
		/**
		 * 又开一个线程
		 *判断message
		 * 装上适配器
		 * 适配器版本的点击事件
		 */
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					adapter = new NewsAdapter(context, newsList);//适配器
					listView.setAdapter(adapter);//设置适配器
					listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//这一部分是点击之后转到新闻内容页面
							/**
							 * 获取位置,把数据装进news
							 * intent切换布局
							 * 传输数据
							 * 启动
							 */
							News news = newsList.get(position);//往定好数据框架的news里面传入数据
							Intent intent = new Intent(getActivity(), NewsDisplayActivity.class);//转到展示新闻的界面
							intent.putExtra("news_url", news.getNewsUrl());//把要打开的网址给他
							startActivity(intent);
						}
					});
				}
			}
		};
		return fragmentView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void getNews(final Context context) {

		new Thread(new Runnable() {
			@Override
			public void run() {
				if (!cache.isNetworkAvailable(context)) {//无网络连接时加载库数据
					newsList = cache.loadCache(MySQLite.NETEASE_NAME);
				} else {
					String[] categories = {"BBM54PGAwangning", "BAI67OGGwangning", "BA8EE5GMwangning",
							"BA8D4A3Rwangning", "BAI6RHDKwangning", "BA10TA81wangning", "BDC4QSV3wangning"};
					//新闻军事财经科技游戏娱乐健康
					String src = "http://3g.163.com/touch/article/list/";
					//手机网易网json数据源
					try {
						for (int i = 0; i < categories.length; i++) {//每个分类爬二十条
							String temp = Jsoup.connect(src + categories[i] + "/0-20.html").get().toString();
							String jsonString = TextUtils.substring(temp, temp.indexOf('(') + 1, temp.lastIndexOf(')'));
							Log.d("json", jsonString);
							JSONObject jsonObject = new JSONObject(jsonString);
							JSONArray jA = jsonObject.getJSONArray(categories[i]);
							//获取json格式字符串，转换成json对象，取对应分类的jsonArray
							for (int j = 0; j < jA.length(); j++) {
								JSONObject jO = (JSONObject) jA.get(j);
								Log.d("docid", jO.get("docid").toString());
								//手机网易json格式->内容（标签）：标题（title）、url（url）、内容提要（digest）、
								//时间和来源（ptime和source）、题图（imgsrc）
								String title = jO.get("title").toString();
								String url = jO.get("url").toString();
								String desc = jO.get("digest").toString().replace('\n', ' ');
								String time = jO.get("source").toString() + " " + jO.get("ptime").toString();
								String imageUrl = jO.get("imgsrc").toString();
								News news = new News(title, url, desc, time, imageUrl);
								newsList.add(news);
							}
						}
						cache.updateCache(newsList, MySQLite.NETEASE_NAME);//更新数据库
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}
		}).start();
	}

}
